package com.xindacloud.sms.portal.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ImportRecipientUtil {

    final static DecimalFormat format = new DecimalFormat("#");

    public static List<String> importRecipient(MultipartFile file) {
        List<String> recipientList = new ArrayList<>();
        try {
            final String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            if (originalFilename.substring(originalFilename.lastIndexOf(".")).equalsIgnoreCase(".csv")) {
                recipientList.addAll(readCSVFile(file.getInputStream()));
            } else {
                recipientList.addAll(readExcel(file.getInputStream()));

            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return recipientList;
    }

    private static List<String> readExcel(InputStream inputStream) throws IOException {
        List<String> recipientList = new ArrayList<>();
        Workbook wb = WorkbookFactory.create(inputStream);
        Sheet sheet = wb.getSheetAt(0);
        /*for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            recipientList.add(row.getCell(0).getStringCellValue());
        }*/
        int i = 1;
        do {
            Row row = sheet.getRow(i);
            Number number = row.getCell(0).getNumericCellValue();
            String phone = format.format(number);
            recipientList.add(phone);
            i++;
        } while (i <= sheet.getLastRowNum());
        log.info("###读取行数为:" + i);
        return recipientList;
    }

    private static List<String> readCSVFile(InputStream inStream) throws IOException {
        List<String> smsPricingList = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8));
        reader.readLine();//第一行信息，为标题信息，不用,如果需要，注释掉
        String line;
        int count = 0;
        while ((line = reader.readLine()) != null) {
            count++;
            String[] item = line.replace("\"", "").split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
            final String phone = item[0];
            smsPricingList.add(phone);
        }
        log.info("###读取行数为:" + count);
        return smsPricingList;
    }
}
